import React, { useCallback, useEffect, useState } from "react";
import { Form, Input, Alert, Button } from "antd";
import { DeleteOutlined, FormOutlined } from "@ant-design/icons";

import { CommonModal } from "@/views/components/CommonModal";
import Typography from "@/pages/OrderModule/common/components/Typography";

import Iconfont from "@/components/IconFont";

import Style from "./index.module.less";
const { TextArea } = Input;

export default React.memo(props => {
	const {
		// 自定义或第三方的表单控件，也可以与 Form 组件一起使用。只要该组件遵循以下的约定：
		// 1/ 提供受控属性 value 或其它与 valuePropName 的值同名的属性。
		// 2/提供 onChange 事件或 trigger 的值同名的事件。
		value,
		onChange,

		allowClear, // input allowClear
		placeholder, // input placeholder
		prefix, //input prefix
		areaPlaceholder, // textArea placeholder
		clearable, // 清空 textArea
		message, // alert => message
		description, // alert => description
		modalProps = {},
		alertProps = { type: "info", showIcon: true },
		autoMultiLine = false,
		maxItem = 0, // 最多保留几个文本（以逗号分隔计算）
		showType = "input", //默认展示input还是textarea
		disabled = false, //是否禁用,
		style,
		className
	} = props;

	if (message) {
		alertProps.message = message;
	}
	if (description) {
		alertProps.description = description;
	}

	if (alertProps.message) {
		alertProps.type = alertProps.type || "info";
		alertProps.showIcon = alertProps.showIcon !== false;
	}

	const [form] = Form.useForm();

	const [open, setOpen] = useState(false);
	const [confirmLoading, setConfirmLoading] = useState(false);
	// const [areaValue, setAreaValue] = useState("");

	const showModal = useCallback(() => {
		const areaText = autoMultiLine ? (value || "").replace(/,/g, "\n") : value || "";
		// setAreaValue(areaText);
		form.setFieldsValue({ areaValue: areaText });
		setOpen(true);
	}, [autoMultiLine, value, setOpen]);

	const handleOk = useCallback(() => {
		form.validateFields().then(async value => {
			const areaText = form.getFieldValue("areaValue");
			let inputText = autoMultiLine ? (areaText || "")?.replace(/\r?\n/g, ",") : areaText || "";
			inputText = inputText.trim();
			const list = inputText.split(",").filter(e => e);
			if (maxItem && list.length > maxItem) {
				inputText = list.slice(0, maxItem).join(",");
			} else {
				inputText = list.join(",");
			}
			onChange?.(inputText);
			setOpen(false);
			modalProps?.onOk?.();
		});
	}, [autoMultiLine, onchange, setOpen, modalProps]);

	const handleCancel = useCallback(() => {
		setOpen(false);
		modalProps?.onCancel?.();
	}, [setOpen, modalProps]);

	const handleClear = useCallback(() => {
		// setAreaValue("");
		form.setFieldsValue({ areaValue: "" });
	}, []);

	const Prefix = useCallback(() => {
		if (prefix) {
			if (typeof prefix == "string") return prefix;
			if (typeof prefix == "function") return prefix();
			if (typeof prefix == "object") return prefix;
			return <prefix />;
		}
		return <></>;
	}, [prefix]);

	return (
		<>
			{showType == "input" ? (
				<Input
					placeholder={placeholder}
					autoComplete="off"
					value={value}
					onChange={onChange}
					allowClear={allowClear}
					prefix={prefix ? <Prefix /> : null}
					suffix={<Iconfont type="icondirect-input" onClick={showModal} />}
					disabled={disabled}
					style={style}
					className={className}
				/>
			) : (
				<div className={Style.textareaBox}>
					<TextArea
						placeholder={placeholder}
						autoComplete="off"
						value={value}
						onChange={onChange}
						allowClear={allowClear}
						prefix={prefix ? <Prefix /> : null}
						suffix={<Iconfont type="icondirect-input" onClick={showModal} />}
						autoSize={{ minRows: 5, maxRows: 10 }}
						disabled={disabled}
					/>
					<span className={Style.textareaIcon}>
						<Iconfont type="icondirect-input" onClick={showModal} />
					</span>
				</div>
			)}
			{	open &&	<CommonModal
				title={{ title: modalProps?.title || placeholder }}
				width={modalProps?.width || 449}
				open={open}
				onOk={handleOk}
				confirmLoading={confirmLoading}
				onCancel={handleCancel}
				// zIndex={props.zIndex || 1000}
				footer={
					<div className={Style.footer_btn_flex}>
						{clearable && (
							<Button type="text" onClick={handleClear}>
								<Iconfont type="icona-qingkong1" style={{ color: "#ff4d4f" }} />
								清空
							</Button>
							//
						)}

						<div>
							<Button {...(modalProps.okButtonProps || [])} onClick={handleCancel}>
								{modalProps.cancelText || "取消"}
							</Button>
							<Button {...(modalProps.cancelButtonProps || [])} type="primary" onClick={handleOk}>
								{modalProps.okText || "确定"}
							</Button>
						</div>
					</div>
				}
			>
				<Form form={form}>
					{alertProps.message && <Alert showIcon message={<Typography as="s1">{alert}</Typography>} {...alertProps} />}
					<div className={Style.common_modal_content}>
						<Form.Item
							name="areaValue"
							rules={
								maxItem && [
									{
										validator: (rule, value) => {
											const valuesArray = value.split(",");
											if (valuesArray.length > maxItem) {
												return Promise.reject(new Error("数据不能超过500个"));
											}
											return Promise.resolve();
										}
									}
								]
							}
						>
							<TextArea
								// value={areaValue}
								// onChange={onChange}
								placeholder={areaPlaceholder || ""}
								autoSize={{ minRows: 5, maxRows: 10 }}
							/>
						</Form.Item>
					</div>
				</Form>
			</CommonModal>}
		</>
	);
});
